import React, { useState, useEffect } from 'react';
import { Modal, Form, Input, Slider, message, Button } from 'antd';
import FileUpload from '@/components/Custom/FileUpload';
import request from '@/utils/request';
import ReRateInfo from '../ScoreModal/ReRateInfo';

import styles from './index.less';

const { TextArea } = Input;
const AssessmentModal = ({ form, visible, setVisible, onCancel, onOk, list, modalType }) => {
    const { getFieldDecorator } = form;
    const [confirmLoading, setConfirmLoading] = useState(false);
    const [disabled, setDisabled] = useState(false);
    const [textArea, setTextArea] = useState('');
    const [reRateData, setReRateData] = useState('');

    const handleOk = () => {
        form.validateFields(async (err, values) => {
            if (err) return;
            setConfirmLoading(true);
            console.log(values, '============values');
            const { files, ...rest } = values;

            const estimatetaskPayload = modalType === 'estimate' ? { estimationResultId: list.id } : {};
            const reestimatetaskPayload = modalType === 'reCalculate' ? { id: list.id } : {};
            const reRateDataPayload = modalType === 'reCalculate' ? { reEstimationApplyDetail: reRateData } : {};
            const result = await request(
                modalType === 'estimate'
                    ? '/api/oa/v1/work/task/estimation/estimatetask'
                    : '/api/oa/v1/work/task/estimation/reestimatetask',
                {
                    method: 'POST',
                    data: {
                        ...rest,
                        resourceRelation: files ? [files.uploadResourceFile] : [],
                        taskId: list.taskId,
                        ...estimatetaskPayload,
                        ...reestimatetaskPayload,
                        ...reRateDataPayload
                    }
                }
            );
            if (result.code === 10000) {
                message.success('估算成功');
                setVisible(false);
                form.resetFields();
                if (onOk) {
                    onOk();
                }
                setConfirmLoading(false);
            } else {
                message.error(result.msg);
                setConfirmLoading(false);
            }
        });
    };
    const handleCancel = () => {
        if (onCancel) onCancel();
        setVisible(false);
    };
    const formLayout = {
        wrapperCol: { span: 16 },
        labelCol: { span: 6 }
    };

    const handleTextAreaChange = e => {
        const { value } = e.target;
        setTextArea(value);
    };

    const getReRateInfo = async () => {
        const result = await request(`/api/oa/v1/work/task/estimation/getestimationapplyresult/${list.id}`, {
            method: 'GET'
        });
        if (result.code === 10000) {
            setReRateData(result.data);
        } else {
            message.error(result.msg);
        }
    };
    const renderText = () => {
        if (modalType === 'reCalculate') {
            return <div className={styles.text}>当前任务已申请重估，请重新估算！</div>;
        }
        return '';
    };

    useEffect(() => {
        if (
            form.getFieldValue('files') &&
            form.getFieldValue('files').allFileList &&
            form.getFieldValue('files').allFileList.length >= 5
        ) {
            setDisabled(true);
        } else {
            setDisabled(false);
        }
    }, [form.getFieldValue('files')]);

    useEffect(() => {
        if (list.id && modalType === 'reCalculate') {
            getReRateInfo();
        }
    }, [list, modalType]);

    return (
        <Modal
            title={modalType === 'estimate' ? '估算' : '重估'}
            width={864}
            visible={visible}
            confirmLoading={confirmLoading}
            onOk={handleOk}
            destroyOnClose
            onCancel={handleCancel}
        // footer={null}
        >
            <Form {...formLayout}>
                {renderText()}
                <Form.Item label="工作量">
                    <div style={{ display: 'flex' }}>
                        <div style={{ flex: 1, marginRight: 10 }}>
                            {getFieldDecorator('estimationValue', {
                                rules: [
                                    {
                                        required: true,
                                        message: '请选择工作量'
                                    }
                                ]
                            })(<Slider tooltipVisible={false} />)}
                        </div>
                        <div>{form.getFieldValue('estimationValue') || 0}</div>
                    </div>
                </Form.Item>
                <Form.Item label="说明">
                    {getFieldDecorator('content', {
                        rules: [{ min: 1, max: 500, message: '请输入1~500个字符' }],
                        initialValue: null
                    })(<TextArea rows={5} maxLength={500} onChange={handleTextAreaChange} />)}
                    <div style={{ lineHeight: 1, color: '#aaa' }}>
                        还可输入
                        <span style={{ color: 'red' }}>{500 - textArea.length < 1 ? 0 : 500 - textArea.length}</span>字
                    </div>
                </Form.Item>
                <Form.Item
                    label="附件"
                    extra={
                        <span style={{ wordBreak: 'break-all' }}>
                            （支持非运行文件格式，每个文件大小不超过50M，最多上传5个附件）
                        </span>
                    }
                >
                    {form.getFieldDecorator('files')(
                        <FileUpload
                            checkFileSize={50}
                            checkFileSizeMsg="文件大小不能超过50MB！"
                            sysCode="OA"
                            businessCode="Taskinfo"
                            categoryCode="taskEstimationFile"
                            checkFileType="TXT,DOC,DOCX,XLS,XLSX,PPT,PPTX,PDF,EDC,SSP,DWG,EDCS,
                            BMP,JPG,PNG,TIF,GIF,PCX,TGA,EXIF,FPX,SVG,PSD,CDR,PCD,DXF,UFO,EPS,AI,
                            RAW,WMF,WEBP,Xmind,ZIP,rar,zip,CAB,ARJ,LZH,TAR,GZ,ACE,UUE,BZ2,JAR,ISO,rp"
                            checkFileTypeMsg="附件格式不合规，请确认！"
                        >
                            <Button className={styles.attachFile} type="link" disabled={disabled}>
                                添加附件
                            </Button>
                        </FileUpload>
                    )}
                </Form.Item>
            </Form>
            {modalType === 'reCalculate' ? (
                <ReRateInfo {...reRateData} leftTitle="重估申请" fileProp="taskReEstimationFile" />
            ) : null}
        </Modal>
    );
};

export default Form.create()(AssessmentModal);
